import { createRouter, createWebHashHistory, type RouteRecordRaw } from "vue-router";
import Api from '../api'
import utils from '../utils/utils'
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'HomeAd',
    redirect: '/LoginAd',
    component: () => import('@/views/HomeAd.vue'),
    children: [
      {
        path: '/Welcome',
        name: 'WelcomeAd',
        meta: { title: '欢迎' },
        component: () => import('@/views/WelcomeAd.vue'),
      },
      //   {
      //     path: '/dept',
      //     name: 'DeptAd',
      //     meta: { title: '部门管理' },
      //     component: () => import('@/views/DeptAd.vue'),
      //   },
      //   {
      //     path: '/echart',
      //     name: 'EchartAd',
      //     meta: { title: '图表' },
      //     component: () => import('@/views/EchartAd.vue'),
      //   },
      //   {
      //     path: '/menu',
      //     name: 'MenuAd',
      //     meta: { title: '菜单管理' },
      //     component: () => import('@/views/MenuAd.vue'),
      //   },
      //   {
      //     path: '/user',
      //     name: 'UserAd',
      //     meta: { title: '用户管理' },
      //     component: () => import('@/views/UserAd.vue'),
      //   },
      //   {
      //     path: '/role',
      //     name: 'RoleAd',
      //     meta: { title: '角色管理' },
      //     component: () => import('@/views/RoleAd.vue'),
      //   },
      //   {
      //     path: '/leave',
      //     name: 'leaveAd',
      //     meta: { title: '请假管理' },
      //     component: () => import('@/views/leaveAd.vue'),
      //   },
      //   {
      //     path: '/approve',
      //     name: 'ApproveAd',
      //     meta: { title: '审批管理' },
      //     component: () => import('@/views/ApproveAd.vue'),
      //   },
      //   {
      //     path: '/clockin',
      //     name: 'ClockInAd',
      //     meta: { title: '打卡管理' },
      //     component: () => import('@/views/ClockInAd.vue'),
      //   },
      //   {
      //     path: '/drivingtrajectory',
      //     name: 'DrivingTrajectory',
      //     meta: { title: '行驶轨迹' },
      //     component: () => import('@/views/DrivingTrajectory.vue'),
      //   },
      //   {
      //     path: '/resourceview',
      //     name: 'ResourceView',
      //     meta: { title: '行驶轨迹' },
      //     component: () => import('@/views/ResourceView.vue'),
      //   },
    ]
  },
  {
    name: 'LoginAd',
    path: '/LoginAd',
    meta: { title: '登录页面' },
    component: () => import('../views/LoginAd.vue'),
  },
  {
    name: '404Ad',
    path: '/404Ad',
    meta: { title: 'Not Found' },
    component: () => import('../views/404Ad.vue'),
  }

];
//设置动态路由
async function loadAsyncRoutes() {
  const userInfo = window.sessionStorage.getItem('userInfo') || '{}';
  const { token } = JSON.parse(userInfo);
  if (token) {
    let res = await Api.getMenuPermissionList();
    // console.log('res', res);
    const {menuList} = res.data;
    console.log('menuList', menuList);
    let routeList = utils.generatorRoutes(menuList);
    // 清空现有动态路由（如果需要）
    // router.removeRoute('HomeAd');
    routeList.forEach((route: any) => {
      router.addRoute('HomeAd', route);
    });
    // console.log('routeList', routeList);
  }
}

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 退出消除重置路由信息
export function ressetRouter() {
  let routerList = router.getRoutes();
  console.log('routerList', routerList);
  routerList.forEach((route: any) => {
    if (!['LoginAd', '404Ad'].includes(route.name)) {
      router.removeRoute(route.name);
    }
  });

}

router.beforeEach(async (to, _from, next) => {
  // 首先获得token
  const userInfo = window.sessionStorage.getItem('userInfo') || '{}'
  //将token解析成json对象
  const { token } = JSON.parse(userInfo)
  // console.log('token',token);
  // 判断当前路由是否需要登录
  if (to.name) {
    document.title = to.meta.title as string
    if (to.name !== 'LoginAd' && !token) {
      next('/LoginAd')
    } else {
      next()
    }
  } else {
    // 这个时候你还没有添加动态路由，所以你跳转到没有权限的页面，是没有to.name这时候你才开始加载loadAsyncRoutes()
    await loadAsyncRoutes()
    const routes = router.getRoutes().filter(route => route.path === to.path)
    if (routes?.length) {//相当于curRoute存在并curRoute.length也存在
      next({...to,replace: true})//终止当前导航，跳转到新的导航
    } else {
      next('/404Ad')
    }
  }
})
export default router;